let loadings = []
const loadingHandler = Vue => {
  function showLoading(config) {
    const { loading } = config
    if (loading && Vue.prototype.$loading) {
      // 饿了吗的loading层是单例，不需要做loading框的存储
      const loading = Vue.prototype.$loading({
        // 声明一个loading对象
        lock: true, // 是否锁屏
        text: '正在加载...', // 加载动画的文字
        spinner: 'el-icon-loading', // 引入的loading图标
        background: 'rgba(0, 0, 0, 0.3)', // 背景颜色
        // target: '.sub-main',                    // 需要遮罩的区域
        body: true,
        customClass: 'mask' // 遮罩层新增类名
      })
      loadings.push(loading)
    }
    return config
  }
  function hideLoading(response) {
    const config = response.config || {}
    if (config.loading) {
      Vue.nextTick(() => {
        loadings.forEach((t) => {
          t.close()
        })
        loadings = []
        config.loading = false
      })
    }
  }
  return {
    requestResolve: showLoading,
    responseResolve: response => {
      hideLoading(response)
      return response
    },
    responseReject: error => {
      hideLoading(error)
      return Promise.reject(error)
    }
  }
}
export default loadingHandler
